package com.cl.pattern.prototype.deep;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * @ClassName ProtoTypeTarget
 * @Description
 * @Author Small
 * @Date 2020/6/16 16:49
 * @Version 1.0
 **/
public class ProtoTypeTarget extends ProtoType {

    public ProtoTypeTarget(String name) {
        super(name);
        /**
         * 打印这句话主要是想测试下，调用clone方法时是否 执行了构造方法
        */
        System.out.println("调用构造方法");
    }

    @Override
    public ProtoType clone() throws CloneNotSupportedException {
        try{

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(this);

            ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bis);

            ProtoType copy = (ProtoType) ois.readObject();
            return copy;

        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}
